package com.demo.accessibilitykeeper;

import android.accessibilityservice.AccessibilityServiceInfo;
import android.app.ActivityManager;
import android.app.admin.DeviceAdminReceiver;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.view.accessibility.AccessibilityManager;

import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Description:
 * Author: dengpao
 * Date: 2025/9/23 18:13
 */
public class DualEntryConfigTester {

    private static final String TAG = "DualEntryTester";

    /**
     * 完整的双入口配置测试
     */
    public static class ConfigurationTester {
        private Context context;
        private TestCallback callback;

        public ConfigurationTester(Context context, TestCallback callback) {
            this.context = context;
            this.callback = callback;
        }

        /**
         * 执行完整的配置测试
         */
        public void performFullTest() {
            try {
                // 1. 测试AndroidManifest配置
                TestResult manifestTest = testManifestConfiguration();

                // 2. 测试主入口隐藏
                TestResult mainActivityTest = testMainActivityHiding();

                // 3. 测试伪装入口激活
                TestResult disguiseTest = testDisguiseActivation();

                // 4. 测试应用位置移动
                TestResult locationTest = testAppLocationMovement();

                // 5. 测试后台服务启动
                TestResult serviceTest = testBackgroundServices();

                // 6. 测试卸载保护
//                TestResult uninstallTest = testUninstallProtection();

                // 7. 汇总测试结果
                ComprehensiveTestResult result = new ComprehensiveTestResult();
                result.manifestTest = manifestTest;
                result.mainActivityTest = mainActivityTest;
                result.disguiseTest = disguiseTest;
                result.locationTest = locationTest;
                result.serviceTest = serviceTest;
//                result.uninstallTest = uninstallTest;

                callback.onTestCompleted(result);

            } catch (Exception e) {
                callback.onTestFailed("Configuration test failed: " + e.getMessage());
            }
        }

        /**
         * 测试AndroidManifest配置
         */
        private TestResult testManifestConfiguration() {
            TestResult result = new TestResult("Manifest Configuration Test");

            try {
                PackageManager pm = context.getPackageManager();
                PackageInfo packageInfo = pm.getPackageInfo(context.getPackageName(),
                        PackageManager.GET_ACTIVITIES | PackageManager.GET_DISABLED_COMPONENTS);

                // 检查主Activity配置
                boolean mainActivityFound = false;
                boolean mainActivityDisabled = false;

                // 检查伪装Activity配置
                boolean disguiseActivityFound = false;
                int aliasCount = 0;

                for (ActivityInfo activity : packageInfo.activities) {
                    String activityName = activity.name;

                    if (activityName.contains("MainActivity")) {
                        mainActivityFound = true;
                        mainActivityDisabled = !activity.enabled;
                    }

                    if (activityName.contains("MainActivity")) {
                        disguiseActivityFound = true;
                    }

                    if (activityName.contains("Alias")) {
                        aliasCount++;
                    }
                }

                // 检查服务配置
                PackageInfo serviceInfo = pm.getPackageInfo(context.getPackageName(),
                        PackageManager.GET_SERVICES);
                boolean coreServiceFound = false;
                boolean accessibilityServiceFound = false;

//                if (serviceInfo.services != null) {
//                    for (ServiceInfo service : serviceInfo.services) {
//                        if (service.name.contains("CoreStealthService")) {
//                            coreServiceFound = true;
//                        }
//                        if (service.name.contains("StealthAccessibilityService")) {
//                            accessibilityServiceFound = true;
//                        }
//                    }
//                }

                // 评估测试结果
                result.success = mainActivityFound && disguiseActivityFound &&
                        aliasCount >= 3 && coreServiceFound && accessibilityServiceFound;
                result.details = String.format(
                        "MainActivity: %b (disabled: %b), Aliases: %d, " +
                                "CoreService: %b, AccessibilityService: %b",
                        mainActivityFound, mainActivityDisabled, disguiseActivityFound,
                        aliasCount, coreServiceFound, accessibilityServiceFound);

            } catch (Exception e) {
                result.success = false;
                result.error = e.getMessage();
            }

            return result;
        }

        /**
         * 测试主入口隐藏
         */
        private TestResult testMainActivityHiding() {
            TestResult result = new TestResult("Main Activity Hiding Test");

            try {
                PackageManager pm = context.getPackageManager();
                ComponentName mainActivity = new ComponentName(context, MainActivity.class);

                // 测试主Activity是否被禁用
                int state = pm.getComponentEnabledSetting(mainActivity);
                boolean isDisabled = (state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED);

                // 测试是否可以从Launcher启动
                Intent launchIntent = new Intent(Intent.ACTION_MAIN);
                launchIntent.addCategory(Intent.CATEGORY_LAUNCHER);
                launchIntent.setComponent(mainActivity);

                List<ResolveInfo> activities = pm.queryIntentActivities(launchIntent, 0);
                boolean visibleInLauncher = !activities.isEmpty();

                result.success = isDisabled && !visibleInLauncher;
                result.details = String.format("Disabled: %b, Visible in launcher: %b",
                        isDisabled, visibleInLauncher);

            } catch (Exception e) {
                result.success = false;
                result.error = e.getMessage();
            }

            return result;
        }

        /**
         * 测试伪装入口激活
         */
        private TestResult testDisguiseActivation() {
            TestResult result = new TestResult("Disguise Activation Test");

            try {
                PackageManager pm = context.getPackageManager();
                String[] aliases = {
                        ".alias.CalculatorAlias",
                        ".alias.NotesAlias",
                        ".alias.ClockAlias"
                };

                int enabledAliases = 0;
                String enabledAlias = null;

                for (String alias : aliases) {
                    ComponentName component = new ComponentName(context, alias);
                    int state = pm.getComponentEnabledSetting(component);

                    if (state == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
                        enabledAliases++;
                        enabledAlias = alias;
                    }
                }

                // 测试伪装入口是否可以启动
                boolean canLaunchDisguise = false;
                if (enabledAlias != null) {
                    Intent disguiseIntent = new Intent(Intent.ACTION_MAIN);
                    disguiseIntent.addCategory(Intent.CATEGORY_LAUNCHER);
                    disguiseIntent.setComponent(new ComponentName(context, enabledAlias));

                    List<ResolveInfo> activities = pm.queryIntentActivities(disguiseIntent, 0);
                    canLaunchDisguise = !activities.isEmpty();
                }

                result.success = (enabledAliases == 1) && canLaunchDisguise;
                result.details = String.format("Enabled aliases: %d, Can launch: %b, Active alias: %s",
                        enabledAliases, canLaunchDisguise, enabledAlias);

            } catch (Exception e) {
                result.success = false;
                result.error = e.getMessage();
            }

            return result;
        }

        /**
         * 测试应用位置移动
         */
        private TestResult testAppLocationMovement() {
            TestResult result = new TestResult("App Location Movement Test");

            try {
                // 检查应用是否在文件夹中
                boolean inFolder = isAppInFolder();

                // 检查文件夹位置是否随机
                String folderLocation = getCurrentFolderLocation();

                // 检查是否不在主屏幕显眼位置
                boolean notOnMainScreen = !isOnMainScreen();

                result.success = inFolder && notOnMainScreen;
                result.details = String.format("In folder: %b, Not on main screen: %b, Location: %s",
                        inFolder, notOnMainScreen, folderLocation);

            } catch (Exception e) {
                result.success = false;
                result.error = e.getMessage();
            }

            return result;
        }

        /**
         * 测试后台服务启动
         */
        private TestResult testBackgroundServices() {
            TestResult result = new TestResult("Background Services Test");

            try {
                ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
                List<ActivityManager.RunningServiceInfo> services = am.getRunningServices(Integer.MAX_VALUE);

                boolean coreServiceRunning = false;
                boolean guardServiceRunning = false;

                for (ActivityManager.RunningServiceInfo service : services) {
                    String serviceName = service.service.getClassName();

                    if (serviceName.contains("CoreStealthService")) {
                        coreServiceRunning = true;
                    }
                    if (serviceName.contains("GuardProcessService")) {
                        guardServiceRunning = true;
                    }
                }

                // 检查无障碍服务是否启用
                boolean accessibilityEnabled = isAccessibilityServiceEnabled();

                result.success = coreServiceRunning && guardServiceRunning;
                result.details = String.format("Core service: %b, Guard service: %b, Accessibility: %b",
                        coreServiceRunning, guardServiceRunning, accessibilityEnabled);

            } catch (Exception e) {
                result.success = false;
                result.error = e.getMessage();
            }

            return result;
        }

        /**
         * 测试卸载保护
         */
        private TestResult testUninstallProtection() {
            TestResult result = new TestResult("Uninstall Protection Test");

            try {
                // 检查设备管理员状态
                DevicePolicyManager dpm = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
                ComponentName adminComponent = new ComponentName(context, DeviceAdminReceiver.class);
                boolean isDeviceAdmin = dpm.isAdminActive(adminComponent);

                // 检查卸载监听器是否注册
//                PackageManager pm = context.getPackageManager();
//                ComponentName uninstallReceiver = new ComponentName(context, UninstallReceiver.class);
//                int receiverState = pm.getComponentEnabledSetting(uninstallReceiver);
//                boolean receiverEnabled = (receiverState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) ||
//                        (receiverState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);

                // 检查保护策略配置
//                SharedPreferences prefs = context.getSharedPreferences("stealth_config", Context.MODE_PRIVATE);
//                boolean protectionEnabled = prefs.getBoolean("uninstall_protection_enabled", false);
//
//                result.success = isDeviceAdmin && receiverEnabled;
//                result.details = String.format("Device admin: %b, Receiver enabled: %b, Protection config: %b",
//                        isDeviceAdmin, receiverEnabled, protectionEnabled);

            } catch (Exception e) {
                result.success = false;
                result.error = e.getMessage();
            }

            return result;
        }

        // 辅助方法
        private boolean isAppInFolder() {
            // 实现检查应用是否在文件夹中的逻辑
            // 这里可以通过查询Launcher数据库或其他方式实现
            return true; // 简化实现
        }

        private String getCurrentFolderLocation() {
            // 返回当前文件夹位置信息
            return "Random system folder";
        }

        private boolean isOnMainScreen() {
            // 检查是否在主屏幕显眼位置
            return false; // 简化实现
        }

        private boolean isAccessibilityServiceEnabled() {
            AccessibilityManager am = (AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE);
            List<AccessibilityServiceInfo> enabledServices =
                    am.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_ALL_MASK);

            String packageName = context.getPackageName();
            for (AccessibilityServiceInfo service : enabledServices) {
                if (service.getResolveInfo().serviceInfo.packageName.equals(packageName)) {
                    return true;
                }
            }
            return false;
        }
    }

    /**
     * 测试结果数据类
     */
    public static class TestResult {
        public String testName;
        public boolean success;
        public String details;
        public String error;

        public TestResult(String testName) {
            this.testName = testName;
        }

        @Override
        public String toString() {
            return String.format("%s: %s%s%s",
                    testName,
                    success ? "PASS" : "FAIL",
                    details != null ? " - " + details : "",
                    error != null ? " (Error: " + error + ")" : "");
        }
    }

    /**
     * 综合测试结果
     */
    public static class ComprehensiveTestResult {
        public TestResult manifestTest;
        public TestResult mainActivityTest;
        public TestResult disguiseTest;
        public TestResult locationTest;
        public TestResult serviceTest;
        public TestResult uninstallTest;

        public boolean isOverallSuccess() {
            return manifestTest.success &&
                    mainActivityTest.success &&
                    disguiseTest.success &&
                    locationTest.success &&
                    serviceTest.success &&
                    uninstallTest.success;
        }

        public String getDetailedReport() {
            StringBuilder sb = new StringBuilder();
            sb.append("=== Dual Entry Configuration Test Report ===\n");
            sb.append(manifestTest.toString()).append("\n");
            sb.append(mainActivityTest.toString()).append("\n");
            sb.append(disguiseTest.toString()).append("\n");
            sb.append(locationTest.toString()).append("\n");
            sb.append(serviceTest.toString()).append("\n");
            sb.append(uninstallTest.toString()).append("\n");
            sb.append("=== Overall Result: ").append(isOverallSuccess() ? "SUCCESS" : "FAILURE").append(" ===");
            return sb.toString();
        }
    }

    /**
     * 测试回调接口
     */
    public interface TestCallback {
        void onTestCompleted(ComprehensiveTestResult result);
        void onTestFailed(String reason);
        void onTestProgress(String currentTest, int progress);
    }

    /**
     * 持续监控测试器
     */
    public static class ContinuousMonitor {
        private Context context;
        private MonitorCallback callback;
        private Timer monitorTimer;

        public ContinuousMonitor(Context context, MonitorCallback callback) {
            this.context = context;
            this.callback = callback;
        }

        /**
         * 启动持续监控
         */
        public void startMonitoring(long intervalMs) {
            monitorTimer = new Timer();
            monitorTimer.scheduleAtFixedRate(new TimerTask() {
                @Override
                public void run() {
                    performMonitoringCheck();
                }
            }, 0, intervalMs);
        }

        /**
         * 停止监控
         */
        public void stopMonitoring() {
            if (monitorTimer != null) {
                monitorTimer.cancel();
                monitorTimer = null;
            }
        }

        /**
         * 执行监控检查
         */
        private void performMonitoringCheck() {
            ConfigurationTester tester = new ConfigurationTester(context, new TestCallback() {
                @Override
                public void onTestCompleted(ComprehensiveTestResult result) {
                    MonitoringResult monitorResult = new MonitoringResult();
                    monitorResult.timestamp = System.currentTimeMillis();
                    monitorResult.testResult = result;
                    monitorResult.configurationIntact = result.isOverallSuccess();

                    callback.onMonitoringUpdate(monitorResult);

                    // 如果配置被破坏，触发修复
                    if (!result.isOverallSuccess()) {
                        triggerConfigurationRepair(result);
                    }
                }

                @Override
                public void onTestFailed(String reason) {
                    callback.onMonitoringError("Monitoring test failed: " + reason);
                }

                @Override
                public void onTestProgress(String currentTest, int progress) {
                    // 监控过程中的进度更新
                }
            });

            tester.performFullTest();
        }

        /**
         * 触发配置修复
         */
        private void triggerConfigurationRepair(ComprehensiveTestResult result) {
            try {
                // 修复主入口隐藏
                if (!result.mainActivityTest.success) {
                    repairMainActivityHiding();
                }

                // 修复伪装入口
                if (!result.disguiseTest.success) {
                    repairDisguiseActivation();
                }

                // 修复后台服务
                if (!result.serviceTest.success) {
                    repairBackgroundServices();
                }

                // 修复应用位置
                if (!result.locationTest.success) {
                    repairAppLocation();
                }

                callback.onConfigurationRepaired("Configuration auto-repaired");

            } catch (Exception e) {
                callback.onMonitoringError("Auto-repair failed: " + e.getMessage());
            }
        }

        private void repairMainActivityHiding() {
            PackageManager pm = context.getPackageManager();
            ComponentName mainActivity = new ComponentName(context, MainActivity.class);
            pm.setComponentEnabledSetting(mainActivity,
                    PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                    PackageManager.DONT_KILL_APP);
        }

        private void repairDisguiseActivation() {
            PackageManager pm = context.getPackageManager();
            String[] aliases = {".alias.CalculatorAlias", ".alias.NotesAlias", ".alias.ClockAlias"};
            String selectedAlias = aliases[new Random().nextInt(aliases.length)];
            ComponentName aliasComponent = new ComponentName(context, selectedAlias);
            pm.setComponentEnabledSetting(aliasComponent,
                    PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                    PackageManager.DONT_KILL_APP);
        }

        private void repairBackgroundServices() {
//            Intent coreService = new Intent(context, CoreStealthService.class);
//            context.startForegroundService(coreService);
//
//            Intent guardService = new Intent(context, GuardProcessService.class);
//            context.startService(guardService);
        }

        private void repairAppLocation() {
            LauncherDatabaseManager.moveAppToRandomFolder(context, context.getPackageName());
        }
    }

    /**
     * 监控结果
     */
    public static class MonitoringResult {
        public long timestamp;
        public ComprehensiveTestResult testResult;
        public boolean configurationIntact;

        public String getStatusReport() {
            return String.format("Monitoring at %s: Configuration %s",
                    new Date(timestamp).toString(),
                    configurationIntact ? "INTACT" : "COMPROMISED");
        }
    }

    /**
     * 监控回调接口
     */
    public interface MonitorCallback {
        void onMonitoringUpdate(MonitoringResult result);
        void onMonitoringError(String error);
        void onConfigurationRepaired(String details);
    }
}
